package com.shanghaiyimu.yimiyangche.fragment;


import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.shanghaiyimu.yimiyangche.R;
import com.shanghaiyimu.yimiyangche.activity.BaoYangShopSelectActivity;
import com.shanghaiyimu.yimiyangche.activity.CarGoodsActivity;
import com.shanghaiyimu.yimiyangche.activity.DaoLuJiuYuan;
import com.shanghaiyimu.yimiyangche.activity.HuanLunTaiActivity;
import com.shanghaiyimu.yimiyangche.activity.NewCarActivity;
import com.shanghaiyimu.yimiyangche.activity.SearchActivity;
import com.shanghaiyimu.yimiyangche.activity.SecondCarShopActivity;
import com.shanghaiyimu.yimiyangche.activity.WashCarActivity;
import com.shanghaiyimu.yimiyangche.activity.WeizhangActivity;
import com.shanghaiyimu.yimiyangche.adapter.PullToRefreshAdapter;
import com.shanghaiyimu.yimiyangche.bean.GoodsBean;
import com.shanghaiyimu.yimiyangche.utils.AdViewpagerUtil;
import com.shanghaiyimu.yimiyangche.widget.SlideShowView;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class ShouyeFragment extends Fragment {


    public ShouyeFragment() {
        // Required empty public constructor

    }
    private TextView textView,newCar;
    private RelativeLayout meirongxiche,chepinshangcheng,youhuiquan,baoyang,gaizhuang,huanluntai,ershouche,baoxian_re;
    private PullToRefreshListView ptrListView;
    private List<GoodsBean> data = new ArrayList<>();
    private PullToRefreshAdapter adapter;
    private View header;
    private SlideShowView slideShowView;

    private AdViewpagerUtil adViewpagerUtil;
    private ViewPager viewPager;
    private String[] urls = {"http://img0.imgtn.bdimg.com/it/u=2799491813,588820357&fm=21&gp=0.jpg",
            "http://img3.imgtn.bdimg.com/it/u=2414756802,531263205&fm=21&gp=0.jpg",
            "http://img2.imgtn.bdimg.com/it/u=2280771936,3888134874&fm=21&gp=0.jpg",
            "http://img3.imgtn.bdimg.com/it/u=2327585548,1525749689&fm=21&gp=0.jpg",
            "http://b.hiphotos.baidu.com/image/h%3D300/sign=f3d57219d03f8794ccff4e2ee21a0ead/728da9773912b31bd1c15c888218367adbb4e1e6.jpg"};
    private LinearLayout lydots;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_shouye, container, false);
        configImageLoader();
        initView(view);
        initData();
        return view;
    }


    private void initView(View view) {
        textView = (TextView) view.findViewById(R.id.fragment_shouye_bar_search);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(),SearchActivity.class);
                startActivity(intent);
            }
        });

        ptrListView = (PullToRefreshListView) view.findViewById(R.id.shouye_ptr_lv);

        //上拉刷新，下拉加载都支持。
        ptrListView.setMode(PullToRefreshBase.Mode.BOTH);

        header = LayoutInflater.from(getContext()).inflate(R.layout.headview,null);

        baoxian_re = (RelativeLayout) header.findViewById(R.id.baoxian_re);
        baoxian_re.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), NewCarActivity.class));
            }
        });

        viewPager = (ViewPager) header.findViewById(R.id.viewpager_header);
        lydots = (LinearLayout) header.findViewById(R.id.ly_dots);
        slideShowView = new SlideShowView(getContext(),null,0);
        slideShowView = (SlideShowView) header.findViewById(R.id.slideshowView);
        //设置字符串
        String[] texts = new String[]{
                "宜牧养车兴轻公园北门工厂店面正式开业。。。",
                "邓禄普轮胎减价大酬宾，原价1088现在988四轮全安装",
                "你的车保养真的做到位了吗？",
                "车子应该如何保养，机油机滤真的选对了吗？"
        };
        slideShowView.setData(texts);
        adViewpagerUtil = new AdViewpagerUtil(getContext(), viewPager, lydots, 8, 4, urls);
        adViewpagerUtil.initVps();
        adViewpagerUtil.setOnAdItemClickListener(new AdViewpagerUtil.OnAdItemClickListener() {
            @Override
            public void onItemClick(View v, int flag) {
                Toast.makeText(getContext(), "flag:" + flag, Toast.LENGTH_SHORT).show();
            }
        });
//        adViewpagerUtil.setOnAdPageChangeListener(new AdViewpagerUtil.OnAdPageChangeListener() {
//            @Override
//            public void onPageScrollStateChanged(int arg0) {
//            }
//
//            @Override
//            public void onPageScrolled(int arg0, float arg1, int arg2) {
//            }
//
//            @Override
//            public void onPageSelected(int arg0) {
//                if(arg0 == 0)
//                    arg0 = 1;
//                if(arg0 == urls.length + 1)
//                {
//                    arg0 = urls.length;
//                }
//               Toast.makeText(getContext(),arg0,Toast.LENGTH_SHORT).show();
//            }
//        });

        huanluntai = (RelativeLayout) header.findViewById(R.id.huanluntai_header_shou);
        huanluntai.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), HuanLunTaiActivity.class);
                startActivity(intent);
            }
        });

        gaizhuang = (RelativeLayout) header.findViewById(R.id.gaizhuang);
        gaizhuang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), WeizhangActivity.class);
                startActivity(intent);
            }
        });

        baoyang = (RelativeLayout) header.findViewById(R.id.baoyang_relayout);
        baoyang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), BaoYangShopSelectActivity.class);
                startActivity(intent);
            }
        });

        ershouche = (RelativeLayout) header.findViewById(R.id.ershouche);
        ershouche.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), SecondCarShopActivity.class);
                startActivity(intent);
            }
        });
        youhuiquan = (RelativeLayout) header.findViewById(R.id.youhuiquanlayout);
        youhuiquan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), DaoLuJiuYuan.class);
                startActivity(intent);
            }
        });

        meirongxiche = (RelativeLayout) header.findViewById(R.id.meirongxiche);
        meirongxiche.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getContext(), WashCarActivity.class);
                startActivity(intent);
            }
        });

        chepinshangcheng = (RelativeLayout) header.findViewById(R.id.chepinshangcheng);
        chepinshangcheng.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), CarGoodsActivity.class);
                startActivity(intent);
            }
        });




//        newCar = (TextView) header.findViewById(R.id.head_text_newcar);
//        newCar.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Intent intent = new Intent(getContext(), NewCarActivity.class);
//                startActivity(intent);
//            }
//        });

        ptrListView.getRefreshableView().addHeaderView(header);
        adapter = new PullToRefreshAdapter(getContext(),data);
        ptrListView.setAdapter(adapter);

        ptrListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                String label = DateUtils.formatDateTime(
                        getContext(),
                        System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME
                                | DateUtils.FORMAT_SHOW_DATE
                                | DateUtils.FORMAT_ABBREV_ALL);
                // Update the LastUpdatedLabel
                refreshView.getLoadingLayoutProxy()
                        .setLastUpdatedLabel(label);

                new GetDataTask().execute();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                new GetMoreDataTask().execute();
            }
        });


    }

    /**
     * 配置ImageLoder
     */
    private void configImageLoader() {
        // 初始化ImageLoader
        @SuppressWarnings("deprecation")
        DisplayImageOptions options = new DisplayImageOptions.Builder().showStubImage(R.drawable.icon_stub) // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.drawable.icon_empty) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.icon_error) // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true) // 设置下载的图片是否缓存在内存中
                .cacheOnDisc(true) // 设置下载的图片是否缓存在SD卡中
                // .displayer(new RoundedBitmapDisplayer(20)) // 设置成圆角图片
                .build(); // 创建配置过得DisplayImageOption对象

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getContext().getApplicationContext()).defaultDisplayImageOptions(options)
                .threadPriority(Thread.NORM_PRIORITY - 2).denyCacheImageMultipleSizesInMemory()
                .discCacheFileNameGenerator(new Md5FileNameGenerator()).tasksProcessingOrder(QueueProcessingType.LIFO).build();
        ImageLoader.getInstance().init(config);
    }


    private void initData() {
        GoodsBean goodsBean = new GoodsBean();
        goodsBean.setName("大众专用");
        goodsBean.setContent("保质保量，2年损坏可重新更换保质保量，" +
                "2年损坏可重新更换保质保量，2年损坏可重新更换");
        for (int i = 0; i < 10; i++) {
            data.add(i,goodsBean);
        }
        adapter.notifyDataSetChanged();
    }



    private class GetDataTask extends AsyncTask<Void,Void,String>{

        @Override
        protected String doInBackground(Void... params) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String aVoid) {
            GoodsBean goodsBean = new GoodsBean();
            goodsBean.setName("奔驰宝马4个圈");
            goodsBean.setContent("奔驰宝马4个圈奔驰宝马4个圈奔驰宝马4个圈奔驰宝马4个圈奔" +
                    "宝马4个圈奔驰宝马4个圈奔驰宝马4个圈");
            data.clear();
            for (int i = 0; i < 10; i++) {
                data.add(goodsBean);
                adapter.notifyDataSetChanged();
                ptrListView.onRefreshComplete();
            }
        }
    }
    //  地址 、ProgressBar、返回结果
    private class GetMoreDataTask extends AsyncTask<Void,Void,String>{

        @Override
        protected String doInBackground(Void... voids) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            GoodsBean goodsBean = new GoodsBean();
            goodsBean.setName("奔驰宝马4个圈");
            goodsBean.setContent("奔驰宝马4个圈奔驰宝马4个圈奔驰宝马4个圈奔驰宝马4个圈奔" +
                    "宝马4个圈奔驰宝马4个圈奔驰宝马4个圈");
            for (int i = 0; i < 10; i++) {
                data.add(goodsBean);
                adapter.notifyDataSetChanged();
                ptrListView.onRefreshComplete();
            }
        }
    }



}
